﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base;
using UFIDA.U9.CBO.SCM.Item;
using UFIDA.U9.Lot;
using UFSoft.UBF.Business;

namespace ufida.u9.ait.openapi
{
    internal class LotMasterBase
    {
        /// <summary>
        /// 查询批号主档,如果没有则创建
        /// </summary>
        /// <param name="lotCode">批号</param>
        /// <param name="itemCode">料号</param>
        /// <param name="lotInfo">批号信息,可以为空,用于处理效期</param>
        /// <returns>批号主档</returns>
        public static LotMaster SaveEntity(string lotCode,string itemCode, LotMasterInfoData lotInfo)
        {
            string path = $"LotCode='{lotCode}' and ItemCode='{itemCode}'";
            LotMaster lot = LotMaster.Finder.Find(path);
            if(lot == null )
            {
                //查询不到,需要新建
                using (ISession session = Session.Open())
                {
                    lot = LotMaster.Create();
                    lot.DataOwnerOrg = Context.LoginOrg;
                    lot.UsingOrg = Context.LoginOrg;
                    lot.ItemOwnerOrg = Context.LoginOrg;
                    lot.LotCode = lotCode;
                    lot.ItemCode = itemCode;
                    path = $"Code='{itemCode}' and Org={Context.LoginOrg.ID}";
                    ItemMaster item = ItemMaster.Finder.Find(path);
                    if (item == null)
                    {
                        throw new Exception($"查询料品失败,path:[{path}]");
                    }
                    lot.Item = item;
                    lot.ItemName = item.Name;
                    if (item.InventoryInfo?.LotParam?.LotCodingParameter?.LotCodingRules.Count > 0)
                    {
                        lot.LotCodingRule = item.InventoryInfo.LotParam.LotCodingParameter.LotCodingRules[0];
                    }
                    if (lotInfo != null)
                    {
                        if(lotInfo.DisabledDatetime>DateTime.MinValue)
                        {
                            //传入失效日期
                            lot.InvalidTime = lotInfo.DisabledDatetime; //失效日期
                            lot.ValidDate = item.InventoryInfo.LotValidDate; //有效期天数
                            lot.EffectiveDatetime = lot.InvalidTime.AddDays(lot.ValidDate*-1);//生效日期
                        }
                    }


                    session.Commit();
                }
            }
            return lot;
        }
    }
}
